<?PHP

ini_set('include_path',ini_get('include_path').':/home/mermexi/local/lib/PEAR:'); 

require_once('config.php');

// DB init
require_once('DB.php');
$db = DB::connect(sprintf('mysql://%s:%s@%s/%s', HM_DBUSER, HM_DBPASS, HM_DBHOST, HM_DBNAME));
if (PEAR::isError($db)) { die ($db->getMessage()); }
$db->setFetchMode(DB_FETCHMODE_ASSOC);

// $user init
if (isset($_COOKIE['userid'])) $user = $db->getRow('SELECT * FROM users WHERE user_id="' . $_COOKIE['userid'] . '"');
if (!isset($user)) $user = array('user_id' => '', 'name' => '', 'categories' => serialize(array()));
$user['categories'] = unserialize($user['categories']);

function getPuzzle () {

 global $user, $db;

 if ($user['user_id'] == '') return $db->getRow('SELECT * FROM puzzles ORDER BY RAND() LIMIT 1');
 if (count($user['categories'])) $where_clause = ' WHERE puzzle_cat IN (' . join(',', $user['categories']) . ') ';
 $puzzles_sql = 'SELECT puzzles.puzzle_id, puzzles.puzzle_lang1, puzzles.puzzle_lang2 FROM puzzles LEFT JOIN scores ON puzzles.puzzle_id=scores.puzzle_id && scores.user_id="' . $user['user_id'] . '" ' . $where_clause . ' ORDER BY scores.puzzle_score, RAND() LIMIT 5';
 $puzzles = $db->getAll($puzzles_sql);
 return $puzzles[array_rand($puzzles)];

}

// lets start with 40 puzzles
$puzzles = array();

for ($i=0; $i<40; $i++) {
 $puzzles[] = getPuzzle();
}

// now build two arrays, puzzles_lang1 and puzzles_lang2, using puzzle_id as keys

$puzzle_lang1 = array();
$puzzle_lang2 = array();

foreach ($puzzles as $puzzle) {
 // need string keys to avoid reordering issues 
 $puzzle_lang1['id_' . $puzzle['puzzle_id']] = $puzzle['puzzle_lang1'];
}

// shuffle the lang2 array, so it wont be obvious when we build the selects which matches which

shuffle($puzzles);

foreach ($puzzles as $puzzle) {
 $puzzle_lang2['id_' . $puzzle['puzzle_id']] = $puzzle['puzzle_lang2'];
}

// now use the two arrays to populate two select elements:

echo '<html>' . "\r\n";
echo '<head>' . "\r\n";
echo '<link rel="stylesheet" type="text/css" href="hangman.css">' . "\r\n";
echo '<META http-equiv=Content-Type content="text/html; charset=UTF-8">' . "\r\n";
echo '<title>Golosa Russian 101 Matching Game</title>' . "\r\n";
echo '<script type="text/javascript" src="match.js"></script>' . "\r\n";
echo '</head>' . "\r\n";
echo '<body>' . "\r\n";

echo '<select id="match_lang1" size="20">' . "\r\n";
foreach ($puzzle_lang1 as $puzz_id => $lang1) {
 echo sprintf('<option value="%s">%s</option>', $puzz_id, $lang1) . "\r\n";
}
echo '</select>' . "\r\n";

echo '<select id="match_lang2" size="20">' . "\r\n";
foreach ($puzzle_lang2 as $puzz_id => $lang1) {
 echo sprintf('<option value="%s">%s</option>', $puzz_id, $lang1) . "\r\n";
}
echo '</select>' . "\r\n";

echo '</body>' . "\r\n";
echo '</html>' . "\r\n";

?>
